package org.example;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PetManager {
    public boolean isAvailable(String petName) throws SQLException {
        String sql = "SELECT 1 FROM pets WHERE name = ? AND status = 'available'";
        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, petName);
            return stmt.executeQuery().next();
        }
    }

    public void markAsAdopted(String petName) throws SQLException {
        String sql = "UPDATE pets SET status = 'adopted' WHERE name = ?";
        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, petName);
            stmt.executeUpdate();
        }
    }
    public void recordAdoption(String petName, String adopterName, String phone) throws SQLException {
        // 直接插入 pet_name，不再用 pet_id
        String sql = "INSERT INTO adoption_records (pet_name, adopter_name, adopter_phone, adoption_date) VALUES (?, ?, ?, ?)";
        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, petName);          // ← 宠物名字
            stmt.setString(2, adopterName);      // ← 领养人姓名
            stmt.setString(3, phone);            // ← 电话
            stmt.setTimestamp(4, Timestamp.valueOf(LocalDateTime.now()));
            stmt.executeUpdate();
        }
    }

    public void adoptPetByName(String petName, String adopterName, String phone) throws SQLException {
        if (!isAvailable(petName)) {
            throw new SQLException("宠物不存在或已被领养");
        }
        markAsAdopted(petName);
        recordAdoption(petName, adopterName, phone);
    }
    public List<Map<String, String>> getAdoptionRecords() throws SQLException {
        List<Map<String, String>> records = new ArrayList<>();
        String sql = "SELECT adopter_name, adopter_phone, pet_name,adoption_date FROM adoption_records ORDER BY adoption_date DESC";

        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {

            while (rs.next()) {
                Map<String, String> record = new HashMap<>();
                record.put("name", rs.getString("adopter_name"));
                record.put("phone", rs.getString("adopter_phone"));
                record.put("petName", rs.getString("pet_name"));
                record.put("date", rs.getString("adoption_date"));
                records.add(record);
            }
        }
        return records;
    }
    // 检查宠物名字是否已存在（避免重复）
    public boolean petExists(String name) throws SQLException {
        String sql = "SELECT 1 FROM pets WHERE name = ?";
        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, name);
            return stmt.executeQuery().next();
        }
    }

    // 添加新宠物
    public void addPet(String name, String species, String breed, int age, int price, String description) throws SQLException {
        if (petExists(name)) {
            throw new SQLException("宠物名字 \"" + name + "\" 已存在，请换一个名字！");
        }

        String sql = "INSERT INTO pets (name, species, breed, age, price, status, description, create_time) " +
                "VALUES (?, ?, ?, ?, ?, 'available', ?, NOW())";

        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, name);
            stmt.setString(2, species);
            stmt.setString(3, breed);       // ← 关键：breed 必须在字段列表里！
            stmt.setInt(4, age);
            stmt.setInt(5, price);
            stmt.setString(6, description);

            stmt.executeUpdate();
        }
    }

    public void updatePet(String name, String species, String breed, int age, double price, String description)
            throws SQLException {
        String sql = "UPDATE pets SET species = ?, breed = ?, age = ?, price = ?, description = ? " +
                "WHERE name = ? AND status = 'available'";

        try (Connection conn = JDBCDemo.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, species);
            stmt.setString(2, breed);
            stmt.setInt(3, age);
            stmt.setDouble(4, price);
            stmt.setString(5, description);
            stmt.setString(6, name);

            int rows = stmt.executeUpdate();
            if (rows == 0) {
                throw new SQLException("宠物不存在、已被领养，或名字不匹配，无法修改");
            }
        }
    }
}